// pages/route/daily/details/details.js
const app = getApp();
const service = require('../../../../utils/service.js');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 路线id
    lineId: null,
    // 选择的日期
    chooseTime: null,
    // 路线类型
    routeType: null,
    // 选择的班次
    timetableIndex: 0,
    // 班次表
    classesData: [],
    // 成人票数
    adultTicketCount: 0,
    // 儿童票数
    childrenTicketCount: 0,
    // 选择的联系人
    liaison: {},
    // 电话前缀
    mobileHeader: '+86',
    // 最终价
    finallyPrice: 0.00
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    this.setData({
      lineId: options.lineId || null,
      chooseTime: options.chooseTime || null,
      routeType: options.routeType || null
    })
  },

  // 获取详细信息
  loadData() {
    let that = this;
    let params = {
      lineId: this.data['lineId'],
      chooseTime: this.data['chooseTime']
    }
    service.getConnect(service.api.getDailyRouteDetails, params).then(function(res) {
      that.setData(res.data);
      wx.hideLoading();
    });
  },

  // 票数减少
  bindTicketCountDown(e) {
    let params = e.currentTarget.dataset.params + 'TicketCount';
    if (this.data[params] >= 1) {
      this.data[params] = this.data[params] - 1;
      let finallyPrice = this.data['adultTicketCount'] * this.data['lineData']['adultPrice'] +
        this.data['childrenTicketCount'] * this.data['lineData']['childrenPrice'];
      this.setData({
        [params]: this.data[params],
        finallyPrice: parseFloat(finallyPrice).toFixed(2),
        coupon: null
      })
    }
  },

  // 票数增加
  bindTicketCountUp(e) {
    let params = e.currentTarget.dataset.params + 'TicketCount';
    if (this.data['classesData'][this.data['timetableIndex']]['standbyTicket'] >
      (this.data['adultTicketCount'] + this.data['childrenTicketCount'])) {
      this.data[params] = this.data[params] + 1;
      let finallyPrice = this.data['adultTicketCount'] * this.data['lineData']['adultPrice'] +
        this.data['childrenTicketCount'] * this.data['lineData']['childrenPrice'];
      this.setData({
        coupon: null,
        [params]: this.data[params],
        finallyPrice: parseFloat(finallyPrice).toFixed(2),
      })
    } else {
      wx.showToast({
        title: '余票不足',
        image: '/images/center/7.png'
      })
    }
  },

  // 选择时间
  bindPickerChange(e) {
    this.setData({
      timetableIndex: e.detail.value,
      adultTicketCount: 0,
      childrenTicketCount: 0
    })
  },

  // 选择联系人
  bindSelectLiaison() {
    wx.navigateTo({
      url: '../../../center/liaison/liaison?source=route',
    })
  },

  // 选择电话前缀
  bindSelectMobileHeader() {
    let that = this;
    let itemList = ['+86', '+853', '+852']
    wx.showActionSheet({
      itemList: itemList,
      success(res) {
        that.setData({
          mobileHeader: itemList[res.tapIndex]
        })
      }
    })
  },

  // 选择优惠券
  toSelectCoupon() {
    let money = this.data['adultTicketCount'] * this.data['lineData']['adultPrice'] +
      this.data['childrenTicketCount'] * this.data['lineData']['childrenPrice'];
    wx.navigateTo({
      url: '/pages/route/selectCoupon/selectCoupon?money='+ money
      + '&type=' + this.data.routeType,
    })
  },

  // 立即购买
  bindBuyNow() {
    let that = this;
    let data = this.data;
    if (data['adultTicketCount'] === 0 && data['childrenTicketCount'] === 0) {
      app.showConfirm('提示', '请选择要购买的票数', false);
      return;
    }
    if (!data['liaison']['id']) {
      app.showConfirm('提示', '请选择联系人', false, function() {
        wx.navigateTo({
          url: '../../../center/liaison/liaison?source=route',
        })
      });
      return;
    }
    let param = {
      // formId: e.detail.formId,
      orderKey: data['orderKey'],
      chooseTime: data['chooseTime'],
      shiftTime: data['classesData'][data['timetableIndex']]['shift'],
      contactId: data['liaison']['id'],
      adultNumber: data['adultTicketCount'],
      childrenNumber: data['childrenTicketCount']
    };

    data['coupon'] && (param['coupon'] = data['coupon']['id']);
    data['coupon'] && (param['userCouponId'] = data['coupon']['userCouponId']);
    console.log(param);
    console.log('--------------------------------------');
    service.getConnect(service.api.sumbitDailyRouteOrder, param).then(function(res) {
      console.log(res);
      wx.hideLoading();
      that.doWxPay(res.data);
    });
  },

  // 调起微信支付
  doWxPay(e) {
    let that = this;
    if (e.appId) {
      wx.requestPayment({
        timeStamp: e.timeStamp,
        nonceStr: e.nonceStr,
        package: e.package,
        signType: e.signType,
        paySign: e.paySign,
        success(res) {
          console.log(res);
          wx.showToast({
            title: '支付成功~',
            mask: true
          })
          wx.showLoading({
            title: '请稍后...',
            mask: true
          });
          that.checkPayStatus(e.orderSn);
        },
        fail(res) {
          console.log(res);
          app.showConfirm('提示', '支付失败,是否前往订单页', true, function() {
            wx.navigateTo({
              url: '/pages/order/details/details?orderSn=' + e.orderSn,
            })
          }, function() {
            that.loadData();
          });
        }
      })
    } else {
      wx.showToast({
        title: '支付成功~',
        mask: true
      })
      that.checkPayStatus(e.orderSn);
    }
  },

  checkPayStatus(orderSn) {
    let that = this;
    service.getConnect(service.api.checkOrderPayStatus, {
      orderSn: orderSn
    }).then(function(res) {
      wx.hideLoading();
      console.log(res);
      if (res.data.isPay === 1) {
        // 跳转订单详情
        // wx.redirectTo({
        //   url: '/pages/order/details/details?orderSn=' + orderSn,
        // })
        // 跳转支付结果
        wx.navigateTo({
          url: '/pages/order/payResult/index?orderSn=' + orderSn,
        })
      } else {
        setTimeout(function() {
          that.checkPayStatus(orderSn);
        }, 1000);
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {
    app.pageOnloadInit(this, app);
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    this.loadData();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {
    clearInterval(this.data.setInter);
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {
    this.loadData();
    wx.stopPullDownRefresh();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {
    let wxappStyle = wx.getStorageSync('wxappStyle');
    return {
      title: app.globalData['wxappStyle']['wxappTitle'] || wxappStyle['wxappTitle'],
      path: '/pages/index/index'
    }

  }
})